package com.tan.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;


import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

@Configuration

public class DruidConfig {
    //绑定总配置文件的内容
    @ConfigurationProperties(prefix = "spring.datasource")
    @Bean
    public DataSource druidDataSource()
    {
        return new DruidDataSource();
    }

    @Bean
    //后台监控：类似web.xml
    public ServletRegistrationBean statViewServlet()
    {
        ServletRegistrationBean<StatViewServlet> bean = new ServletRegistrationBean<>(new StatViewServlet(),"/druid/*");
        //后台需要有人登陆，账号密码配置
        HashMap<String,String> initParameters = new HashMap<>();
        //增加配置
        initParameters.put("loginUsername","admin");
        initParameters.put("loginPassword","123456");

        //允许谁可以访问
        initParameters.put("allow","");//""为所有人能访问，"localhost"单个能访问
//        禁止访问initParameters.put("kuangshen","192.168.11.123");
        bean.setInitParameters(initParameters);//设置初始化参数
        return bean;
    }

    //filter
    @Bean
    public FilterRegistrationBean webStatFilter()
    {
        FilterRegistrationBean bean = new FilterRegistrationBean();
        bean.setFilter(new WebStatFilter());
        //可以过滤哪些请求呢？

        Map<String,String> initParamters = new HashMap<>();

        //这些东西不进行统计
        initParamters.put("exclusions","*.js,.css,/druid/*");
        bean.setInitParameters(initParamters);
        return bean;
    }
}
